import { v4 as uuidv4 } from 'uuid';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { rspc } from '@fill/client';
import { Button, Col, Form, Row, Space, Typography, notification } from 'antd';
import { useContext, useEffect, useState } from 'react';
import { UploadFile } from '../report/Upload';
import type { IUploadFile } from '../../util';
import { APPROVAL_STATE, HANDLE_STATUS, MB_KEYS, STATUS_TEXT, STATUS_VALUE } from '../../constants/default';
import { Export } from '../record/Export';
import { checkStateUpdate } from '../../util/state';
import { FillContext } from '../app/Fill';
import { CONFIG_KEYS } from '../../constants/config';

export const RECTIFICATION = 'rectification';
export interface IRectification {
  uuid: string
  user: string
  completed_at?: string
  examine: number
  status: STATUS_TEXT
  attachment: IUploadFile[]
  publish: IUploadFile[]
  inside: IUploadFile[]
  node: string
  next: string
  node_id: string
  state: string
  state_text?: string
}

export const Content = () => {
  const [form] = Form.useForm<any>();
  const { config } = useContext(FillContext);
  const { data, refetch } = rspc.useQuery(['configs.key', {
    arg: {
      key: RECTIFICATION,
    },
  }]);
  const saveConfig = rspc.useMutation('configs.save');

  const [formData, setFormData] = useState<IRectification>({
    uuid: '',
    user: '',
    examine: 0,
    status: STATUS_TEXT.NORMAL,
    attachment: [],
    publish: [],
    inside: [],
    node: '',
    next: '',
    node_id: '',
    state: '',
    state_text: '',
  });

  useEffect(
    () => {
      const values = data?.value && JSON.parse(data?.value);
      data?.value && setFormData({
        ...JSON.parse(data.value),
        status: HANDLE_STATUS[values.status as keyof typeof HANDLE_STATUS],
        state_text: APPROVAL_STATE[values.state as keyof typeof APPROVAL_STATE],
      });
      data?.value && form.setFieldsValue({
        ...JSON.parse(data.value),
        status: HANDLE_STATUS[values.status as keyof typeof HANDLE_STATUS],
        state_text: APPROVAL_STATE[values.state as keyof typeof APPROVAL_STATE],
      });
    },

    // eslint-disable-next-line react-hooks/exhaustive-deps
    [data],
  );

  async function handleSubmit(tmp = false) {
    try {
      await form.validateFields();
    }
    catch (error) {
      notification.error({
        message: '校验失败',
      });
      return;
    }

    const values = form.getFieldsValue();
    const record = JSON.parse(data?.value || '{}');
    record.uuid = record?.uuid || uuidv4();
    const value = JSON.stringify({
      ...{
        user: '',
        examine: 0,
        status: STATUS_VALUE.NORMAL,
        attachment: [],
        publish: [],
        inside: [],
        node: '',
        next: '',
        node_id: '',
        state: '',
      },
      ...record,
      ...values,
      attachment: values.attachment,
      status: tmp ? STATUS_VALUE.PENDING : STATUS_VALUE.PROCESSED,
    });
    await saveConfig.mutateAsync({
      arg: {
        key: RECTIFICATION,
        value,
      },
    });

    refetch();

    notification.success({
      placement: 'topRight',
      message: `${tmp ? '暂存' : '保存'}成功`,
    });
  }

  return (
    <>
      <br></br>
      <Row justify="space-between" align="middle">
        <Col md={1}>
          {/* <Space>
            <Typography.Text>整改报告状态:</Typography.Text>
            <Typography.Text type="danger">超期未提交</Typography.Text>
          </Space> */}
        </Col>
        <Col xxl={4} xl={6}>
          <Space>
            <Button type="primary" disabled={!checkStateUpdate(formData.state || '')} onClick={() => handleSubmit(true)}>暂存</Button>
            <Button type="primary" disabled={!checkStateUpdate(formData.state || '')} onClick={() => handleSubmit()}>保存</Button>
            <Export module="rectification" text="导出提报" disabled={!checkStateUpdate(formData.state || '')} />
          </Space>
        </Col>
      </Row>

      <br />

      <div style={{
        width: 860,
        margin: 'auto',
      }}>
        <Row justify="center">
          <Col>
            <Typography.Title level={3}>{config[CONFIG_KEYS.F_XCZDX_NAME_]}</Typography.Title>
          </Col>
        </Row>
        <br />
        <ProForm<IRectification>
          layout="horizontal"
          labelCol={{
            span: 6,
          }}
          labelWrap={true}
          grid
          form={form}
          initialValues={formData}
          submitter={false}
          readonly={!checkStateUpdate(formData.state || '')}
          onFinish={async () => {

          }}
        >
          <ProFormText name="user" label="编辑人" placeholder="请输入编辑人" colProps={{
            span: 24,
          }} labelCol={{
            span: 3,
          }} rules={[
            {
              required: true,
              message: '请输入编辑人',
            },
          ]} width={670} />
          <ProFormText disabled label="审批状态" placeholder={''} name="state_text" colProps={{
            span: 12,
          }} width={240} />
          <ProFormText disabled placeholder={''} label="处理状态" name="status" width={240} colProps={{
            span: 12,
          }} />
          <Col span={24}>
            <ProForm.Item label="党内通报稿" labelCol={{
              span: 3,
            }} name="attachment" extra="支持 doc、docx、pdf、xls、xlsx、jpg 、png、jpeg、txt、ext文件格式，最大不超过200M">
              <UploadFile type={MB_KEYS.NOTIFICATION} files={formData.attachment} onChange={files => form.setFieldValue('attachment', files)} readonly={!checkStateUpdate(formData.state || '')} />
            </ProForm.Item>
          </Col>
          <Col span={24}>
            <ProForm.Item label="社会公开稿" labelCol={{
              span: 3,
            }} name="publish" extra="支持 doc、docx、pdf、xls、xlsx、jpg 、png、jpeg、txt、ext文件格式，最大不超过200M">
              <UploadFile type={MB_KEYS.PUBLISH} files={formData.publish} onChange={files => form.setFieldValue('publish', files)} readonly={!checkStateUpdate(formData.state || '')} />
            </ProForm.Item>
          </Col>
          <Col span={24}>
            <ProForm.Item label="不宜向社会公开事项的说明" labelCol={{
              span: 3,
            }} name="inside" extra="支持 doc、docx、pdf、xls、xlsx、jpg 、png、jpeg、txt、ext文件格式，最大不超过200M">
              <UploadFile type={MB_KEYS.INISIDE} files={formData.inside} onChange={files => form.setFieldValue('inside', files)} readonly={!checkStateUpdate(formData.state || '')} />
            </ProForm.Item>
          </Col>
        </ProForm>
      </div>
    </>
  );
};
